//
// Created by kriko on 2021/7/2.
//

#include <csapp.h>
#include <cstdio>
#include <sbuf.h>

#include "echoserver-pre.h"

const int NTHREADS = 4;
const int SBUFSIZE = 16;

sbuf_t sbuf;

void *thread(void*);

int main(int argc, char* argv[]) {
    int listenfd, connfd;
    socklen_t clientlen;
    sockaddr_storage clientaddr;
    pthread_t pid;
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <port>\n", argv[0]);
        return -1;
    }

    listenfd = Open_listenfd(atoi(argv[1]));

    sbuf_init(&sbuf, SBUFSIZE);
    for(int i = 0; i < NTHREADS; ++i) {
        pthread_create(&pid, NULL, thread, NULL);
    }

    while(1) {
        clientlen = sizeof clientaddr;
        connfd = Accept(listenfd, (SA*)&clientaddr, &clientlen);
        sbuf_insert(&sbuf, connfd);
    }

    return 0;
}

void* thread(void* args) {
    pthread_detach(pthread_self());
    while(1) {
        int connfd = sbuf_remove(&sbuf);
        echo_cnt(connfd);
        Close(connfd);
    }
}
